package com.qiguliuxing.dts.admin.web;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.admin.dao.IordersAll;
import com.qiguliuxing.dts.admin.dao.IordersTemplate;
import com.qiguliuxing.dts.admin.dao.dto.DailyOrderPageQuery;
import com.qiguliuxing.dts.admin.listener.IordersTemplateListener;
import com.qiguliuxing.dts.admin.service.AdminDailyOrderService;
import com.qiguliuxing.dts.admin.service.AdminIorderStockService;
import com.qiguliuxing.dts.admin.service.AdminProductProductionService;
import com.qiguliuxing.dts.admin.util.AuthSupport;
import com.qiguliuxing.dts.admin.util.excel.core.StringUtils;
import com.qiguliuxing.dts.core.util.ResponseUtil;
import com.qiguliuxing.dts.db.domain.DailyOrder;
import com.qiguliuxing.dts.db.domain.IoralStock;
import com.qiguliuxing.dts.db.domain.Iorders;
import com.qiguliuxing.dts.db.domain.ProductProduction;
import com.qiguliuxing.dts.db.service.IoralStockService;
import com.qiguliuxing.dts.db.service.ProductProductionService;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Retention;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Date;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/dailyOrder")
@Validated
public class AdminDailyOrderController {

    @Autowired
    private AdminDailyOrderService adminDailyOrderService;
    @Autowired
    private ProductProductionService productProductionService;
    @Autowired
    private AdminProductProductionService adminProductProductionService;
    @Autowired
    private IoralStockService ioralStockService;

    private static final Logger logger = LoggerFactory.getLogger(AdminDailyOrderController.class);

    @RequiresPermissions("admin:dailyOrder:list")
    @RequiresPermissionsDesc(menu = {"碘131生产发货管理", "每日分装统计"}, button = "查找")
    @PostMapping("/list")
    public Object list(@RequestBody DailyOrderPageQuery dailyOrderPageQuery) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 碘订单->查询,请求参数:instrumentNumber:{},instrumentName:{},page:{}", dailyOrderPageQuery.getPage(), dailyOrderPageQuery.getLimit());
        //需要区分数据权限，如果属于品牌商管理员，则需要获取当前用户管理品牌店铺
        /*   List<Integer> brandIds = null;*//*
         *//*if (adminDataAuthService.isBrandManager()) {*//*
         *//*        brandIds = adminDataAuthService.getBrandIds();
            logger.info("运营商管理角色操作，需控制数据权限，brandIds:{}",JSONObject.toJSONString(brandIds));

            if (brandIds == null || brandIds.size() == 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("total", 0L);
                data.put("items", null);

                logger.info("【请求结束】商品管理->商品管理->查询,响应结果:{}", JSONObject.toJSONString(data));
                return ResponseUtil.ok(data);
          *//**//*  }*//*
         *//*     }*/

        List<IoralStock> list =ioralStockService.querySelective(1,20,"","volume","desc");

        for(IoralStock ioralStock:list){
           ioralStock.setSelected(false);
            ioralStockService.updateById(ioralStock);
        }
        String startTime="";
        String endTime="";
        String sort=dailyOrderPageQuery.getSort();
        String order=dailyOrderPageQuery.getOrder();
        List<String> ste=new ArrayList<>();
        ste=dailyOrderPageQuery.getStartToEnd();
        if(ste!=null && !ste.isEmpty()) {
            startTime = ste.get(0).substring(0, 10);
            endTime = ste.get(1).substring(0, 10);
            logger.info(ste.toString());
            logger.info(startTime + endTime);
        }
        return adminDailyOrderService.list(dailyOrderPageQuery.getCustomerName(),startTime, endTime, /*dailyOrderPageQuery.getDailyOrder(),*/ dailyOrderPageQuery.getPage(), dailyOrderPageQuery.getLimit(), sort,order);
    }
   /* @RequiresPermissions("admin:dailyOrder:listNull")
    @RequiresPermissionsDesc(menu = {"碘131生产发货管理", "每日数据汇总"}, button = "刷新")
    @PostMapping("/list")
    public Object listNull(@RequestBody DailyOrderPageQuery dailyOrderPageQuery) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 碘订单->查询,请求参数:instrumentNumber:{},instrumentName:{},page:{}", dailyOrderPageQuery.getPage(), dailyOrderPageQuery.getSize());

        return adminDailyOrderService.list(dailyOrderPageQuery.getDailyOrder(), dailyOrderPageQuery.getPage(), dailyOrderPageQuery.getSize()*//*, sort,order*//*);
    }*/
/*   @RequiresPermissions("admin:dailyOrder:calculate")
   @RequiresPermissionsDesc(menu = {"碘131生产发货管理", "每日数据汇总"}, button = "计算分装信息")
   @PostMapping("/calculate")
    public Object calculate(@RequestBody DailyOrderPageQuery){



        return null;
    }*/

/*    @GetMapping("/catAndBrand")
    public Object catAndBrand() {
        return adminInstrumentService.catAndBrand();
    }*/

    /**
     * 编辑商品
     *
     * @param iordersAll
     * @return
     */
    @RequiresPermissions("admin:dailyOrder:update")
    @RequiresPermissionsDesc(menu = {"碘131生产发货管理", "每日数据汇总"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody IordersAll iordersAll) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 碘131生产发货管理->订单列表->编辑,请求参数:{}", JSONObject.toJSONString(iordersAll));

        return adminDailyOrderService.update(iordersAll);
    }

    /*@RequiresPermissions("admin:dailyOrder:insertMany")
    @RequiresPermissionsDesc(menu = {"碘131生产发货管理", "每日数据汇总"}, button = "导入")
    @GetMapping("/insertMany")
    public boolean addUser(@RequestParam("file") MultipartFile file) {
        boolean a = false;
        String fileName = file.getOriginalFilename();
        try {
            *//* a = itestService.batchImport(fileName, file);*//*
        } catch (Exception e) {
            e.printStackTrace();
        }
        return a;
    }*/

    /**
     * 删除器材
     *
     * @param dailyOrder
     * @return
     */
    @RequiresPermissions("admin:dailyOrder:delete")
    @RequiresPermissionsDesc(menu = {"碘131生产发货管理", "每日数据汇总"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody DailyOrder dailyOrder) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 碘订单管理->删除,请求参数:{}", JSONObject.toJSONString(dailyOrder));
        logger.info("cxc");
        return adminDailyOrderService.delete(dailyOrder);
    }

    /*@RequiresPermissions("admin:instrument:insertMany")
    public Object insertMany(@RequestBody List<InstrumentAll> list){

        return
    }
*/

    /**
     * 添加商品
     * 哈哈哈哈哈哈哈哈哈
     *
     * @param iordersAll
     * @return
     */
    @RequiresPermissions("admin:dailyOrder:create")
    @RequiresPermissionsDesc(menu = {"碘131生产发货管理", "每日数据汇总"}, button = "新增")
    @GetMapping("/create")
    public Object create(@RequestBody IordersAll iordersAll) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 碘131生产发货管理->订单列表->新增,请求参数:{}", JSONObject.toJSONString(iordersAll));
        DailyOrder dailyOrder = iordersAll.getDailyOrder();


        logger.info(iordersAll.toString());
        return adminDailyOrderService.create(iordersAll);
    }

    @Value("${spring.servlet.multipart.location}")
    private String uploadDir;

       /* @RequiresPermissions("admin:iorder:uploadExcels")*/
//    @RequiresPermissionsDesc(menu = {"碘131生产发货管理", "碘131分装"}, button = "计算分装信息")
    @PostMapping(value = "/uploadExcel", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String uploadExcel(@RequestPart("file") @NotNull MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "文件不能为空");
        }

        String fileName = file.getOriginalFilename();
        if (StringUtils.isBlank(fileName) || !fileName.endsWith(".xlsx")) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "仅支持上传 .xlsx 文件");
        }

        InputStream inputStream = file.getInputStream();
        IordersTemplateListener iordersTemplateListener = new IordersTemplateListener();
        EasyExcel.read(inputStream, IordersTemplate.class, iordersTemplateListener).sheet().doRead();

        List<IordersTemplate> iordersTemplates = iordersTemplateListener.getList();
        if (iordersTemplates != null) {
            for (IordersTemplate it : iordersTemplates) {

                IordersAll iordersAll = new IordersAll();
                DailyOrder iorder = new DailyOrder();

                BeanUtils.copyProperties(it, iorder);
                iorder.setActualCount(it.getActualCount());
                iordersAll.setDailyOrder(iorder);
                adminDailyOrderService.create(iordersAll);
            }
        }
        // 添加更多的处理逻辑
        // ...
        logger.info("XVXwdqwdqwdqdqwdqwd");
/*        return (String) adminDailyOrderService.listNow(iordersTemplates);*/
        return "文件上传成功";
    }

    @RequiresPermissions("admin:dailyOrder:downloadExcel")
    @RequiresPermissionsDesc(menu = {"碘131生产发货管理", "每日数据汇总"}, button = "上传订单")
    @GetMapping("/downloadExcel")
    public String downloadExcel(HttpServletResponse response) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Data");
        logger.info("SDFSDFSDF");
        // 创建Excel文件的内容
        // ...
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 碘131生产发货管理->订单列表->新增,请求参数:{}", JSONObject.toJSONString("已上传excel文件"));
        response.setHeader("Content-Disposition", "attachment; filename=example.xlsx");
        try (OutputStream out = response.getOutputStream()) {
            workbook.write(out);
        }
        logger.info("SDFSDFSDF");
        return "文件上传成功";
    }


    /**
     * 器材详情
     *
     * @param id
     * @return
     */
    @RequiresPermissions("admin:dailyOrder:read")
    @RequiresPermissionsDesc(menu = {"碘131生产发货管理", "每日数据汇总"}, button = "详情")
    @GetMapping("/detail")
    public Object detail(@NotNull Integer id) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 碘订单管理->详情,请求参数,id:{}", id);
        logger.info("hehehehheheh");
        return adminDailyOrderService.detail(id);
    }

    @RequiresPermissions("admin:dailyOrder:read")
    @RequiresPermissionsDesc(menu = {"碘131生产发货管理", "每日数据汇总"}, button = "详情")
    @GetMapping("/more")
    public Object detail2(@NotNull Integer id) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 碘订单->详情,请求参数,id:{}", id);
        logger.info("hehehehheheh");
        return adminDailyOrderService.detail(id);
    }

    @RequiresPermissions("admin:dailyOrder:insertMany")
    @RequiresPermissionsDesc(menu = {"碘131生产发货管理", "碘131分装"}, button = "确认上传")
    @GetMapping("/insertMany")
    public Object addDailyIorders(@RequestParam(value = "list",required = true) List<IordersTemplate> iordersTemplates) {
        boolean a = false;
        double constantNum = -0.0864089775561;
        if (iordersTemplates != null) {
            for (IordersTemplate it : iordersTemplates) {
                IordersAll iordersAll = new IordersAll();
                DailyOrder iorder = new DailyOrder();
                BeanUtils.copyProperties(it, iorder);
//                DateTimeFormatter formatter = new DateTimeFormatter("");
                iorder.setUseTime(LocalDateTime.now());
                iorder.setShowId(it.getShowId());
                iorder.setActualCount(it.getActualCount());
                iordersAll.setDailyOrder(iorder);
                ProductProduction production = productProductionService.queryNewestBatch();
                if (production != null) {
                    // 计算出需要多少天
                    // math.exp()
                    Integer concentration=production.getOralConcentration();
                    double result =concentration * Math.exp(constantNum * (ChronoUnit.DAYS.between(production.getMeasureTine(), LocalDate.parse(it.getUseTime()))));
                    // 计算
                    DecimalFormat decimalFormat = new DecimalFormat("#0.00");
                    float concentrate1 = Float.parseFloat(production.getOralConcentration().toString());// 浓度
                    double volume1 = Double.parseDouble(it.getOrderCount()) / result / it.getPieces() * 1.05;
                    String concentrate=decimalFormat.format(concentrate1);
                    String volume=decimalFormat.format(volume1);
                    it.setSplitQuantity(volume+"");   //实际分装量（活度）

                    it.setActualCount(decimalFormat.format(volume1 * concentration) + "");//实际分装量
                    it.setMaterialBatch(production.getBatchNumber());
                    it.setPieces(it.getPieces());
                }
                adminDailyOrderService.create(iordersAll);
            }
        }
        logger.info("【请求结束】碘订单->订单管理->上传订单至数据库,响应结果:{}", "成功!");
        long total = PageInfo.of(iordersTemplates).getTotal();
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", iordersTemplates);
        logger.info("【请求结束】碘订单管理->仪器列表->查询,响应结果:{}", JSONObject.toJSONString(data));
        return ResponseUtil.ok(data);
    }

}
